let fs = require('fs');
let path = require('path');
let _ = require('lodash');
let { writeFile, beautifyJs } = require('../file');
module.exports = function one2Many(config, relative) {
  let rootRelative = '../../';
  fs.readFile(
    path.join(__dirname, rootRelative, relative, config.source.path),
    (err, data) => {
      if (err) {
        throw err;
      }
      const buf = Buffer.from(data, 'utf8');
      let source = config.source;
      let fileStr = buf.toString();
      let reg = source.reg;
      let jsonArr = [];
      while ((rep = reg.exec(fileStr))) {
        let obj = {};
        source.keys.forEach((item, idx) => {
          obj[item] = rep[idx + 1];
        });
        jsonArr.push(obj);
      }
      let outPath = config.targets.path;
      config.targets.files.forEach(r => {
        let outStr = _.template(r.render)({ items: jsonArr });
        console.log(relative, outPath);
        writeFile(
          path.join(__dirname, rootRelative, relative, outPath, './'),
          r.fileName,
          beautifyJs(outStr)
        );
      });
    }
  );
};
